package com.trade.dao.impl;

import com.trade.dao.*;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.apache.commons.dbcp.BasicDataSource;
import org.hibernate.*;
import java.sql.*;
import java.util.*;
import java.io.*;
import java.text.*;
import com.trade.data.*;
import com.trade.data.type.*;

import com.trade.data.calculation.InstrumentTechnicalCalValuesVO;
import com.trade.data.calculation.MACDValuesVO;
import com.trade.data.calculation.MovingAverageValuesVO;
import com.trade.data.calculation.RSIValuesVO;
import com.trade.data.calculation.BollingerBandValuesVO;

import org.drools.KnowledgeBase;
import org.drools.KnowledgeBaseFactory;
import org.drools.builder.KnowledgeBuilder;
import org.drools.builder.KnowledgeBuilderError;
import org.drools.builder.KnowledgeBuilderErrors;
import org.drools.builder.KnowledgeBuilderFactory;
import org.drools.builder.ResourceType;
import org.drools.compiler.PackageBuilderConfiguration;
import org.drools.io.ResourceFactory;
import org.drools.logger.KnowledgeRuntimeLogger;
import org.drools.logger.KnowledgeRuntimeLoggerFactory;
import org.drools.runtime.StatefulKnowledgeSession;
import org.drools.builder.conf.*;
import org.drools.runtime.rule.WorkingMemoryEntryPoint;
import org.drools.event.rule.DebugWorkingMemoryEventListener;
import org.drools.event.rule.DebugAgendaEventListener;
import org.drools.runtime.process.ProcessInstance;

//import org.drools.process.core.datatype.impl.type.EnumDataType;


public class TestDrools{

	public static void main(String[] args)throws Exception {


		System.setProperty("drools.ruleflow.port", "true");



		String param = "", param_2 = "";
		if( args.length > 0 ){
			param = args[0].trim();
		}

		if( args.length > 1 ){
			param_2 = args[1].trim();
		}

		System.out.println("Args 1:"+param + ", 2:"+param_2);


		ApplicationContext context = new ClassPathXmlApplicationContext(
				"applicationContextTest.xml");

		INSEDataDAO nse = (INSEDataDAO)context.getBean("nseDataDAO");
		final IEquityDAO equity = (IEquityDAO)context.getBean("equityDAO");

		final ILivePriceDAO livePriceDAO = (LivePriceDAO)context.getBean("livePriceDAO");
		final DroolFlowDAO droolFlowDAO = (DroolFlowDAO)context.getBean("droolFlowDAO");

		final StatefulKnowledgeSession  ksession = (StatefulKnowledgeSession)context.getBean("statefulKnowledgeSession");



		final List<String> tickerList = new ArrayList<String>();
		tickerList.add("NIFTY");
		tickerList.add("SBIN");
		//tickerList.add("BHEL");
		//tickerList.add("RANBAXY");
		//tickerList.add("HINDALCO");
		//tickerList.add("INFOSYS");
		//tickerList.add("COAL");
		//tickerList.add("TATASTEEL");


		/*try{

			List<InstrumentVO> allStocks = nse.getAllStockScripts();
			for(InstrumentVO instrumentVO : allStocks){
					//tickerList.add(instrumentVO.getSymbol());
				if( tickerList.contains(instrumentVO.getSymbol())){
					droolFlowDAO.insertObject(instrumentVO);
				}
			}
		}catch(Exception e){*/

			System.out.println("Setting default ticker values");

			InstrumentVO instrumentVO =new InstrumentVO();
			instrumentVO.setSecurityName("");
			instrumentVO.setMarketType("");
			instrumentVO.setSymbol("SBIN");

			InstrumentVO instrumentVO1 =new InstrumentVO();
			instrumentVO1.setSecurityName("");
			instrumentVO1.setMarketType("");
			instrumentVO1.setSymbol("NIFTY");

			InstrumentVO instrumentVO2 =new InstrumentVO();
			instrumentVO2.setSecurityName("");
			instrumentVO2.setMarketType("");
			instrumentVO2.setSymbol("BHEL");

			droolFlowDAO.insertObject(instrumentVO);
			droolFlowDAO.insertObject(instrumentVO1);
			//droolFlowDAO.insertObject(instrumentVO2);
		//}




		if("LIVE".equals( param )){

			HistoricalDataFilterVO historicalDataFilterVO = new HistoricalDataFilterVO();
			historicalDataFilterVO.setTickerList(tickerList);
			historicalDataFilterVO.setInterval(IntervalTimeTypes.T1_YEAR ); // 120 T2_MIN -- T2_MIN_3DAY
			//historicalDataFilterVO.setNoOfPeriod(3); // 3 days
			List<HistoricalDataVO> histList1 = livePriceDAO.getClosePrices(historicalDataFilterVO );

			for(HistoricalDataVO histDataVO :  histList1){
					histDataVO.setIntervalTimeTypes(IntervalTimeTypes.T2_MIN ); //T2_MIN

					droolFlowDAO.insertObject(histDataVO,IntervalTimeTypes.T2_MIN);
					ProcessFilterVO processFilterVO = new ProcessFilterVO();
					processFilterVO.setSymbol( histDataVO.getSymbol() );
					processFilterVO.setHistoricalDataVO( histDataVO );
					ProcessInstance processInstance = droolFlowDAO.startTradeFlowProcess(processFilterVO);
					droolFlowDAO.fireAllRules();

			}

			new Thread(new Runnable() {

				@Override
				public void run() {
					System.out.println("\n\n\n2 MIN Live Price Thread started\n\n\n");
					while(true){
						try{
							HistoricalDataFilterVO historicalDataFilterVO = new HistoricalDataFilterVO();
							historicalDataFilterVO.setTickerList(tickerList);
							historicalDataFilterVO.setInterval(IntervalTimeTypes.T2_MIN_1DAY);
							//historicalDataFilterVO.setNoOfPeriod(1);
							List<HistoricalDataVO> histList = livePriceDAO.getIntradayClosePrices(historicalDataFilterVO );

							for(HistoricalDataVO histDataVO :  histList){
								histDataVO.setIntervalTimeTypes(IntervalTimeTypes.T2_MIN);
								droolFlowDAO.insertObject(histDataVO,IntervalTimeTypes.T2_MIN);

								ProcessFilterVO processFilterVO = new ProcessFilterVO();
								processFilterVO.setSymbol( histDataVO.getSymbol() );
								processFilterVO.setHistoricalDataVO( histDataVO );
								droolFlowDAO.startTradeFlowProcess(processFilterVO);
								droolFlowDAO.fireAllRules();

							}

							System.out.println();
							Thread.sleep(120000);
						}catch(Exception e){
							System.out.println(e.getLocalizedMessage());
						}
					}
				}
			}).start();

			/*new Thread(new Runnable() {

				@Override
				public void run() {
					System.out.println("\n\n\n3 SEC Live Price Thread started\n\n\n");
					while(true){
						try{
							HistoricalDataFilterVO historicalDataFilterVO = new HistoricalDataFilterVO();
							historicalDataFilterVO.setTickerList(tickerList);
							historicalDataFilterVO.setInterval(IntervalTimeTypes.T3_SEC);
							historicalDataFilterVO.setNoOfPeriod(1);
							List<HistoricalDataVO> histList = livePriceDAO.getIntradayClosePrices(historicalDataFilterVO );

							for(HistoricalDataVO histDataVO :  histList){
								histDataVO.setIntervalTimeTypes(IntervalTimeTypes.T2_MIN);
								droolFlowDAO.insertObject(histDataVO,IntervalTimeTypes.T2_MIN);
								ProcessFilterVO processFilterVO = new ProcessFilterVO();
								processFilterVO.setSymbol( histDataVO.getSymbol() );
								processFilterVO.setHistoricalDataVO( histDataVO );
								droolFlowDAO.startTradeFlowProcess(processFilterVO);
							}

							System.out.println();
							Thread.sleep(3000); // Price Update on Every 3 sec
						}catch(Exception e){
							System.out.println(e.getLocalizedMessage());
						}
					}
				}
			}).start();*/



		}else{
			String fileName = "";

			if("SBI".equals( param ) && "W".equals(param_2) ){
				fileName = "SBI_TICKS_W.properties";
			}else if("SBI".equals( param ) && "D".equals(param_2) ){
				fileName = "SBI_TICKS_D.properties";
			}else if("SBI".equals( param ) && "30M".equals(param_2) ){
				fileName = "SBI_TICKS_30M.properties";
			}

			Scanner inputSBIN = null ;
			if("SBI".equals( param )){
				inputSBIN = new Scanner( new FileInputStream("./temp/"+fileName));
			}

			if("NIFTY".equals( param ) && "W".equals(param_2) ){
				fileName = "NIFTY_TICKS_W.properties";
			}else if("NIFTY".equals( param ) && "D".equals(param_2) ){
				fileName = "NIFTY_TICKS_D.properties";
			}else if("NIFTY".equals( param ) && "30M".equals(param_2) ){
				fileName = "NIFTY_TICKS_30M.properties";
			}

			System.out.println("file :"+fileName);

			Scanner input = new Scanner( new FileInputStream("./temp/"+fileName));



					int i=0;
						try{
							if("SBI".equals( param ) || "SBI&NIFTY".equals( param )){

								System.out.println("\n\n\nSBI Price Thread started\n\n\n");

								while( inputSBIN.hasNextLine()){

									Thread.sleep(10);

										String data[] = inputSBIN.nextLine().split(",");

										HistoricalDataVO histDataVO = new EquityIntradayDataVO();
										histDataVO.setSymbol("SBIN");
										histDataVO.setDate(new java.util.Date());
										histDataVO.setClose(Double.parseDouble(data[1]));
										histDataVO.setHigh(Double.parseDouble(data[2]) );
										histDataVO.setLow(Double.parseDouble(data[3]));
										histDataVO.setOpen(Double.parseDouble(data[4]));
										histDataVO.setVolume(Double.parseDouble(data[5]));
										histDataVO.setIntervalTimeTypes(IntervalTimeTypes.T2_MIN);

										if( histDataVO.getClose() == histDataVO.getHigh()
											&&
											histDataVO.getClose() == histDataVO.getLow()
											&&
											histDataVO.getClose() == histDataVO.getOpen()

											){
											System.out.println("SBI Skip Data close - "+ histDataVO.getClose() + ", high - "
												+ histDataVO.getHigh());
											continue;
										}

										droolFlowDAO.insertObject(histDataVO,IntervalTimeTypes.T2_MIN);
										ProcessFilterVO processFilterVO = new ProcessFilterVO();
										processFilterVO.setSymbol( histDataVO.getSymbol() );
										processFilterVO.setHistoricalDataVO( histDataVO );
										ProcessInstance processInstance = droolFlowDAO.startTradeFlowProcess(processFilterVO);
										droolFlowDAO.fireAllRules();
										//ksession.dispose();


								}

							}

							/*if("NIFTY".equals( param ) || "SBI&NIFTY".equals( param )){
								System.out.println("\n\nNifty 2 Min Price started -----------\n\n\n");

								try{
										while( input.hasNextLine()){

											Thread.sleep(20);

											String data[] = input.nextLine().split(",");

											HistoricalDataVO histDataVO = new EquityIntradayDataVO();
											histDataVO.setSymbol("NIFTY");
											histDataVO.setDate(new java.util.Date());
											histDataVO.setClose(Double.parseDouble(data[1]));
											histDataVO.setHigh(Double.parseDouble(data[2]) );
											histDataVO.setLow(Double.parseDouble(data[3]));
											histDataVO.setOpen(Double.parseDouble(data[4]));
											histDataVO.setVolume(Double.parseDouble(data[5]));
											histDataVO.setIntervalTimeTypes(IntervalTimeTypes.T2_MIN);

											if( histDataVO.getClose().doubleValue() == histDataVO.getHigh().doubleValue()
												&&
												histDataVO.getClose().doubleValue() == histDataVO.getLow().doubleValue()
												&&
												histDataVO.getClose().doubleValue() == histDataVO.getOpen().doubleValue()

												){
												System.out.println("NIFTY Skip Data close - "+ histDataVO.getClose() + ", high - "
													+ histDataVO.getHigh());
												continue;
											}

											System.out.println(""+histDataVO);

											droolFlowDAO.insertObject(histDataVO,IntervalTimeTypes.T2_MIN);
											ProcessFilterVO processFilterVO = new ProcessFilterVO();
											processFilterVO.setSymbol( histDataVO.getSymbol() );
											processFilterVO.setHistoricalDataVO( histDataVO );
											ProcessInstance processInstance = droolFlowDAO.startTradeFlowProcess(processFilterVO);
											droolFlowDAO.fireAllRules();
											//ksession.dispose();
										}
								}catch(Exception e){
									System.out.println("Error - "+e.getLocalizedMessage());
								}

							}*/


							if("NIFTY".equals( param ) || "SBI&NIFTY".equals( param )){
								System.out.println("\n\nNifty 30 Min Price started -----------\n\n\n");

								try{
										input.reset();
										while( input.hasNextLine()){

											Thread.sleep(20);

											String data[] = input.nextLine().split(",");

											HistoricalDataVO histDataVO = new EquityIntradayDataVO();
											histDataVO.setSymbol("NIFTY");
											histDataVO.setDate(new java.util.Date());
											histDataVO.setClose(Double.parseDouble(data[1]));
											histDataVO.setHigh(Double.parseDouble(data[2]) );
											histDataVO.setLow(Double.parseDouble(data[3]));
											histDataVO.setOpen(Double.parseDouble(data[4]));
											histDataVO.setVolume(Double.parseDouble(data[5]));
											histDataVO.setIntervalTimeTypes(IntervalTimeTypes.T30_MIN);

											if( histDataVO.getClose().doubleValue() == histDataVO.getHigh().doubleValue()
												&&
												histDataVO.getClose().doubleValue() == histDataVO.getLow().doubleValue()
												&&
												histDataVO.getClose().doubleValue() == histDataVO.getOpen().doubleValue()

												){
												System.out.println("NIFTY Skip Data close - "+ histDataVO.getClose() + ", high - "
													+ histDataVO.getHigh());
												continue;
											}

											System.out.println(""+histDataVO);

											droolFlowDAO.insertObject(histDataVO,IntervalTimeTypes.T30_MIN);
											ProcessFilterVO processFilterVO = new ProcessFilterVO();
											processFilterVO.setSymbol( histDataVO.getSymbol() );
											processFilterVO.setHistoricalDataVO( histDataVO );
											ProcessInstance processInstance = droolFlowDAO.startTradeFlowProcess(processFilterVO);
											droolFlowDAO.fireAllRules();
											//ksession.dispose();
										}
								}catch(Exception e){
									System.out.println("Error - "+e.getLocalizedMessage());
								}

							}




						}catch(Exception e){
							System.out.println("Error - "+e.getLocalizedMessage());
						}




		}


		//logger.close();

	}


}